<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04-轨道控制器_实现交互</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body {
      width: 100%;
      height: 100%;
    }
  </style>
</head>

<body>
  <script type="module">
    import * as THREE from "three";
    // 创建场景
    const scene = new THREE.Scene();
    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      1,
      1000
    );
    camera.position.set(2, 200, 20);
    camera.lookAt(0, 0, 0);
    // 创建渲染器 
    const renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    // 设置渲染器大小
    renderer.setSize(window.innerWidth, window.innerHeight);
    // 把渲染的canvas内容添加到body
    document.body.appendChild(renderer.domElement);

    // 设置网格
    const gridHelper = new THREE.GridHelper(100, 10, "red", "blue");
    // 设置物体
    const cube = new THREE.Mesh(
      new THREE.BoxGeometry(10, 10, 10),
      new THREE.MeshBasicMaterial({
        color: 0xff11ff
      })
    );
    // 添加网格和物体到场景
    scene.add(gridHelper, cube);

    function animate() {
      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }

    // 添加动画并渲染
    animate();

    let isDown = false;
    let startX = 0;
    let startY = 0;
    let currentX = 0;
    let currentY = 0;
    // 监听鼠标
    renderer.domElement.addEventListener("mousedown", (e) => {
      isDown = true;
      startX = e.clientX;
      currentX = e.clientX;
      startY = e.clientY;
      currentY = e.clientY;
    });
    renderer.domElement.addEventListener("mousemove", (e) => {
      if (isDown) {
        const distanceX = e.clientX - startX;
        const distanceY = e.clientY - startY;
        currentX += distanceX * 0.01;
        currentY += distanceY * 0.01;
        startX = e.clientX;
        startY = e.clientY;
        camera.position.x = 40 * Math.cos(currentX);
        // camera.position.y = 40 * Math.sin(currentY);
        camera.position.z = 40 * Math.sin(currentX);
        camera.lookAt(0, 0, 0);
      }
    });
    renderer.domElement.addEventListener("mouseup", (e) => {
      isDown = false;  
    });

    // 监听屏幕变化
    window.addEventListener("resize", function () {
      // 更新摄像头
      camera.aspect = window.innerWidth / window.innerHeight;
      // 更新摄像机的投影矩阵
      camera.updateProjectionMatrix();
      // 更新渲染器
      renderer.setSize(window.innerWidth, window.innerHeight);
      // 设置渲染器的像素比
      renderer.setPixelRatio(window.devicePixelRatio);
    });
  </script>
</body>

</html>